package com.auntvt.timo.jpax.core.utils;

import org.apache.commons.lang3.reflect.TypeUtils;
import org.springframework.lang.Nullable;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.Map;

/**
 * Type工具
 *
 * @author 小懒虫 <auntvt@163.com>
 * @date 2021/5/26
 */
public class TypeUtil extends TypeUtils {

    /**
     * 将类的泛型格式化为字符串形式：<a, b, ...>
     *
     * @param clazz 类
     * @return 格式化字符串
     */
    public static String formatGenericToString(@Nullable Class<?> clazz) {
        if (clazz == null) {
            throw new NullPointerException("类不能为空");
        }

        // 获取对象泛型
        Type genericType = clazz.getGenericSuperclass();
        Map<TypeVariable<?>, Type> typeArguments = getTypeArguments((ParameterizedType) genericType);
        if (typeArguments.size() == 0) {
            return "";
        }

        // 拼装格式化泛型字符串
        StringBuffer buffer = new StringBuffer("<");
        typeArguments.forEach((typeVariable, type) -> {
            buffer.append(((Class<?>) type).getSimpleName()).append(", ");
        });
        buffer.delete(buffer.length() - 2, buffer.length());
        return buffer.append(">").toString();
    }
}
